package cn.bdqn.mh.filter;

import cn.bdqn.mh.utils.Constants;
import cn.bdqn.mh.utils.JavascriptAlertHelper;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;

/**
 * 创建人:  zhang
 * 创建日期: 2020/7/17 11:14
 */
@WebFilter(value ={"/user/*","/myhouse/*"})
public class AuthFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器初始化了");
    }

    //过滤方法
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        System.out.println("过滤器执行了");
        response.setContentType(Constants.CONTENT_TYPE_TEXT);
        //PrintWriter out=response.getWriter();//不能这样写，springboot会产生一个错误
        OutputStream out=response.getOutputStream();//得到输出流
        OutputStreamWriter writer=new OutputStreamWriter(out);//写对象
        HttpServletRequest httpServletRequest=(HttpServletRequest) request;//转到子类对象
        HttpSession session=httpServletRequest.getSession();//获取当前会员session对象，其实就是键值对，类似map
        //System.out.println("sessionid="+session.getId());//这个编号也是写入查到客户端cookie里的
        Object obj=session.getAttribute(Constants.SESSION_USER_NAME);
        String js=null;
        if(obj==null) {
            //这样我们认为，你没有登录,
            //获取当前请求的url，并作为传参给login
            String url=httpServletRequest.getContextPath()+"/login.html?returnurl="+httpServletRequest.getRequestURI();
            js= JavascriptAlertHelper.alert("必须登录后才能访问", url);
            //out.write(js);
            writer.write(js);
            writer.flush();
            writer.close();
            out.flush();
            out.close();
        }else {
            //登录成功，那么放行
            chain.doFilter(request, response);
        }


    }
}
